package br.edu.ufcg.dsc.services;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import br.edu.ufcg.dsc.domain.Reservation;

public class ReservationService extends BaseService {

	private static final long ONE_HOUR = 60 * 60 * 1000;
	private static final long ONE_DAY = 24 * ONE_HOUR;
	private static long timestamp = 0;

	public static void persist(Reservation r) {
		EntityTransaction tx = entity.getTransaction();
		tx.begin();
		try {
			entity.persist(r);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		}
	}

	@SuppressWarnings("unchecked")
	public static List<Reservation> findAllReservations() {
		Query q = entity
				.createQuery("SELECT r FROM br.edu.ufcg.dsc.domain.Reservation r");

		List<Reservation> r = q.getResultList();
		return r;
	}

	public static void deleteOldReservations() {
		long now = System.currentTimeMillis();

		if (now < timestamp + ONE_HOUR)
			return;

		timestamp = now;

		EntityTransaction tx = entity.getTransaction();
		tx.begin();

		List<Reservation> allReservations = findAllReservations();

		for (Reservation r : allReservations) {
			if (HolidayService.countBusinessDaysSince(r.getStartDate()) > 1)
				entity.remove(r);
		}
		entity.flush();
		
		tx.commit();
	}
	
	static {
		
		deleteOldReservations();
		TimerTask t = new TimerTask() {
			
			@Override
			public void run() {
				deleteOldReservations();
			}
		};
		
		GregorianCalendar calendar = new GregorianCalendar();
		
		calendar.setTimeInMillis(calendar.getTimeInMillis() + ONE_DAY);
		
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		
		Timer timer = new Timer(true);
		
		Date tomorrow = calendar.getTime();
		
		timer.schedule(t, tomorrow, ONE_DAY);
	}
}
